/*
 * @Author jiangzhiwei
 * @Date 2023-07-23 20:13:46
 * @LastEditors jiangzhiwei
 * @LastEditTime 2023-07-28 11:30:30
 * @FilePath \test-cron\src\components\yc-cron\components\options\common-last-week-option\index.js
 * @Description 每月最后一个周几选项
 */
import { defineComponent } from 'vue-demi'
import { h } from '../../../utils/domutil'
import { getWeekMap } from '../../../utils/config'
import { QUARTS_TYPE, VALUE_NAME, VALUE_EMIT_NAME, PARSE_ERROR_EMIT_NAME } from '../../../utils/constant'
import optionMixin from '../mixins/optionmixin'
import CommonLi from '../../base/common-li'
import CommonInputNumber from '../../base/common-input-number'
import { emitValue } from '../../../utils/componentutil'

const NAME = 'yc-cron-last-week-option'
const regexp = /^([0-7])L$/

export default defineComponent({
  name: NAME,
  mixins: [optionMixin],
  data () {
    return {
      /** 周几 */
      week: 1,
      /** 总天数 */
      total: 7,
      /** 最大值。0~7 或 1~7最大值都是7 */
      max: 7,
      /** 开始值 */
      startNum: this.type === QUARTS_TYPE ? 1 : 0
    }
  },
  watch: {
    /** 根据表达式变化来设置选项内容 */
    expression: {
      handler (value) {
        if (value && value.indexOf('L') !== -1) { // 表示匹配
          const arr = regexp.exec(value)
          if (arr) { // 表示匹配，即格式正确
            const num = Number.parseInt(arr[1])
            if (num < this.startNum) {
              emitValue(this, `值不能小于${this.startNum}`, PARSE_ERROR_EMIT_NAME)
            } else if (num > this.max) {
              emitValue(this, `值不能大于${this.max}`, PARSE_ERROR_EMIT_NAME)
            } else {
              this.week = num
              emitValue(this, this.label)
            }
          } else {
            emitValue(this, '格式错误', PARSE_ERROR_EMIT_NAME)
          }
        } else { // 不匹配
          this.tryCancelCheck()
        }
      },
      immediate: true
    }
  },
  methods: {
    /** 时间范围更新 */
    onUpdate (value) {
      this.week = value
      // emitValue(this, this.label)
      this.tryEmitExpression()
    },
    /** 获取表达式 */
    getExpression () {
      return `${this.week}L`
    }
  },
  render () {
    return h(
      CommonLi,
      {
        props: { [VALUE_NAME]: this[VALUE_NAME], label: this.label },
        on: { [VALUE_EMIT_NAME]: this.onInput }
      },
      [
        this.descriptions[0],
        h(
          CommonInputNumber,
          {
            props: {
              [VALUE_NAME]: this.week,
              min: this.startNum,
              max: this.max,
              valueMap: getWeekMap(this.type),
              controlsPosition: 'right',
              size: 'small'
            },
            on: { [VALUE_EMIT_NAME]: value => this.onUpdate(value) }
          }
        ),
        this.descriptions[1]
      ]
    )
  }
})